<?php
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Http\Client;

class VideosController extends AppController{

    public $_page_num = 30;
    public function initialize()
    {
        parent::initialize();
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：获取指定的视频
   * */
    public function getInfo()
    {
        $id = $this->request->getData("id");
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        $videos = $this->Videos->findById($id)->first();
        if(empty($videos)){
            $this->G->error("video_error");
            return null;
        }
        $video_info = $this->getvideoinfo($videos['qvid']);
        if(empty($video_info['basicInfo'])){
            $this->G->error($video_info['codeDesc']);
            return null;
        }
        $videos['play_url'] = $video_info['basicInfo']['sourceVideoUrl'];
        $this->loadComponent('CategoryContentCache');
        $cate_id = $this->CategoryContentCache->getCategories('videos',$id);
        $videos['category_id'] = empty($cate_id) ? 0 : $cate_id[0];
        $this->loadModel('Categories');
        $this->loadModel('CategoryContents');
        $parent_id = $this->Categories->findById($videos['category_id'])->first();
        if(empty($parent_id)){
            $parent_id['parent_id'] = 0;
        }
        $videotopic_id = $this->CategoryContents->find()
            ->select(['content_id'])
            ->where(['content_type'=>'videotopics','category_id'=>$parent_id['parent_id']])
            ->first();
        $this->loadComponent('TextareaCache');
        $content = $this->TextareaCache->getVal('videos', $id);
        $this->loadComponent('ContentFormat');
        $videos['content']  = empty($content) ? '' : $this->ContentFormat->add($content['content']);
        $videos['videoTopic_id'] = empty($videotopic_id['content_id']) ? 0:$videotopic_id['content_id'];
        $videos['add_time'] = date('Y-m-d H:i:s', $videos['add_time']);
        $this->G->success("Success", $videos);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.30
   * ps：获取对应分类
   * */
    public function getCategories()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $videoTopicId = $this->request->getData("videoTopicId");
        if(!empty($videoTopicId)){
            $this->loadComponent('CategoryContentCache');
            $cate_ids = $this->CategoryContentCache->getCategories('videotopics', $videoTopicId);
        }else{
            $this->loadComponent('SysconfigCache');
            $cate_ids[] = $this->SysconfigCache->getVal('free_video_category_id');
        }
        $data = [];
        if(!empty($cate_ids[0])){
            $this->loadModel('Categories');
            $data = $this->Categories->get($cate_ids[0]);
            $children = $this->Categories->find('children', ['for' => $cate_ids[0]])->find('threaded')->toArray();
            $data['children'] = $children;
        }
        $this->G->success("Success", $data);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.28
   * ps：删除视频
   * */
    public function deleteVideo()
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $ids = $this->request->getData("ids");
        if(empty($ids) || !is_array($ids)){
            $this->G->error("ids_error");
            return null;
        }
        $this->loadComponent('VideoCache');
        $this->loadComponent('CategoryContentCache');
        $this->loadModel('CategoryContents');
        $this->loadComponent('TextareaCache');
        foreach ($ids as $k=>$v){
            $this->CategoryContentCache->deleteCategories('videos', $v);
            $this->VideoCache->deleteCache($v);
            $this->TextareaCache->delete('videos', $v);
        }
        $this->VideoCache->deleteList();
        $this->Videos->deleteAll(['id in'=>$ids]);
        $this->loadModel('VideoLevels');
        $this->VideoLevels->deleteAll(['video_id in'=>$ids]);
        $this->CategoryContents->deleteAll(['content_id in'=>$ids,'content_type'=>'videos']);
        $this->G->success("Success");
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.28
   * ps：修改视频
   * */
    public function updateVideo()
    {
        $id = $this->request->getData("id");
        $category_id = $this->request->getData("category_id");
        $title = $this->request->getData("title");
        $qvid = $this->request->getData("qvid");
        $author = $this->request->getData("author");
        $enabled = $this->request->getData("enabled");
        $view_group = $this->request->getData("view_group");
        $year = $this->request->getData("year");
        $videotopic_id = $this->request->getData("videotopic_id");
        $content = $this->request->getData("content");
        $level_id = $this->request->getData("level_id");
        if(empty($content)){
            $this->G->error("content_error");
            return null;
        }
        if(!is_numeric($id)){
            $this->G->error("id_error");
            return null;
        }
        if(empty($title)){
            $this->G->error("title_error");
            return null;
        }
        if(empty($author)){
            $this->G->error("author_error");
            return null;
        }
//        if(!is_numeric($level_id)){
//            $this->G->error("level_id_error");
//            return null;
//        }
        if(!in_array($enabled, [0,1])){
            $this->G->error("enabled_error");
            return null;
        }
        if(strlen(trim($qvid)) < 1 || strlen(trim($qvid)) > 20){
            $this->G->error("qvid_error");
            return null;
        }
        $videos = $this->Videos->findById($id)->select(['id'])->first();
        if(empty($videos)){
            $this->G->error('video_not_found');
            return null;
        }
        $video_info = $this->getvideoinfo($qvid);
        if(empty($video_info['basicInfo'])){
            $this->G->error($video_info['codeDesc']);
            return null;
        }
        $video = $this->Videos->newEntity();
        $video->id = $id;
        $video->title = $title;
        $video->author = $author;
        $video->qvid = $qvid;
        $video->img = $video_info['basicInfo']['coverUrl'];
        $video->duration = $video_info['basicInfo']['duration'];
        $video->enabled = $enabled;
        $video->view_group = $view_group;
        $video->year = $year;
        if(!empty($videotopic_id)){
            $video->videotopic_id = $videotopic_id;
        }
        $this->Videos->save($video);
        $this->loadModel('CategoryContents');
        $category_contents = $this->CategoryContents->find()
            ->select(['id'])
            ->where(['content_type' => 'videos', 'content_id'=>$id])
            ->first();
        if(!empty($category_id)){
            if(empty($category_contents)){
                $category_content = $this->CategoryContents->newEntity();
                $category_content->category_id = $category_id;
                $category_content->content_type = 'videos';
                $category_content->content_id = $id;
                $this->CategoryContents->save($category_content);
            }else{
                $this->CategoryContents->query()
                    ->update()
                    ->set(['category_id'=>$category_id])
                    ->where(['id' => $category_contents['id']])
                    ->execute();
            }
        }else{
            if(!empty($category_contents)){
                $this->CategoryContents->deleteAll(['id'=>$category_contents['id']]);
            }
        }
        if(!empty($level_id)){
            $this->loadModel('VideoLevels');
            $this->VideoLevels->query()
                ->update()
                ->set(['level_id'=>$level_id])
                ->where(['video_id' => $id])
                ->execute();
        }
        $this->loadComponent('TextareaCache');
        $this->loadComponent('ContentFormat');
        $content  = $this->ContentFormat->clean($content)[0];
        $this->TextareaCache->update('videos', $id, $content);
        $this->loadComponent('VideoCache');
        $this->loadComponent('CategoryContentCache');
        $this->CategoryContentCache->deleteCategories('videos', $id);
        $this->VideoCache->deleteList();
        $this->VideoCache->deleteCache($id);
        $this->G->success('Success');

    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.28
   * ps：新增视频
   * */
    public function addVideo()
    {
        $category_id = $this->request->getData("category_id");
        $title = $this->request->getData("title");
        $qvid = $this->request->getData("qvid");
        $author = $this->request->getData("author");
        $enabled = $this->request->getData("enabled");
        $view_group = $this->request->getData("view_group");
        $year = $this->request->getData("year");
        $videotopic_id = $this->request->getData("videotopic_id");
        $content = $this->request->getData("content");
        $level_id = $this->request->getData("level_id");
        if(empty($content)){
            $this->G->error("content_error");
            return null;
        }
        if(empty($title)){
            $this->G->error("title_error");
            return null;
        }
        if(!is_numeric($author)){
            $this->G->error("author_error");
            return null;
        }
//        if(!is_numeric($level_id)){
//            $this->G->error("level_id_error");
//            return null;
//        }
        if(!in_array($enabled, [0,1])){
            $this->G->error("enabled_error");
            return null;
        }
        if(strlen(trim($qvid)) < 1 || strlen(trim($qvid)) > 20){
            $this->G->error("qvid_error");
            return null;
        }
        $video_info = $this->getvideoinfo($qvid);
        if(empty($video_info['basicInfo'])){
            // $this->G->error($video_info['codeDesc']);
            $this->G->error("未配置视频点播服务");
            return null;
        }
        $video = $this->Videos->newEntity();
        $video->title = $title;
        $video->author = $author;
        $video->qvid = $qvid;
        $video->img = $video_info['basicInfo']['coverUrl'];
        $video->duration = $video_info['basicInfo']['duration'];
        $video->enabled = $enabled;
        $video->view_group = $view_group;
        $video->year = $year;
        if(!empty($videotopic_id)){
            $video->videotopic_id = $videotopic_id;
        }
        $video->add_time = time();
        $video_save = $this->Videos->save($video);
        if(!empty($level_id)){
            $this->loadModel('VideoLevels');
            $video_level = $this->VideoLevels->newEntity();
            $video_level->video_id = $video_save->id;
            $video_level->level_id = $level_id;
            $this->VideoLevels->save($video_level);
        }
        $this->loadComponent('TextareaCache');
        $this->loadComponent('ContentFormat');
        $content  = $this->ContentFormat->clean($content)[0];
        $this->TextareaCache->add('videos', $video_save->id, $content);
        if(!empty($category_id)){
            $this->loadModel('CategoryContents');
            $category_contents = $this->CategoryContents->newEntity();
            $category_contents->category_id = $category_id;
            $category_contents->content_type = 'videos';
            $category_contents->content_id = $video_save->id;
            $this->CategoryContents->save($category_contents);
        }
        $this->loadComponent('VideoCache');
        $this->VideoCache->deleteList();
        $this->G->success('Success');
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.18
   * ps：获取视频列表
   * */
    public function getList()
    {
        $data = $this->request->getData();
        $this->loadComponent('VideoCache');
        if(!empty($data)){
            ksort($data, SORT_NATURAL);
        }
        $key = md5(json_encode($data));
        $data = $this->VideoCache->getList($data);
        $list = ['pageTotal'=>0,'list'=>[]];
        if(empty($data[$key]['list'])){
            $this->G->success('Success', $list);
            return null;
        }
        $list['pageTotal'] = ceil($data[$key]['total']/$this->_page_num);
        foreach ($data[$key]['list'] as $k=>$v){
            $video = $this->VideoCache->getVal($v);
            if(empty($video)){
                continue;
            }
            $video['add_time'] = date('Y-m-d H:i:s', $video['add_time']);
            $video['duration'] = floor($video['duration']/60).':'.$video['duration']%60;
            $list['list'][] = $video;
        }
        $this->G->success('Success', $list);
    }

    /*
   * create by phpstorm
   * author：Ming
   * date：2020.04.18
   * ps：获取视频内容
   * */
    public function getVideo($view_group)
    {
        if(!$this->request->is("post")){
            $this->G->error("post_error");
            return null;
        }
        $video_id = $this->request->getData("video_id");
        if(!is_numeric($video_id)){
            $this->G->error("id_error");
            return null;
        }
        $this->loadComponent('VideoCache');
        $this->loadComponent('UserCache');
        $info = $this->VideoCache->getVal($video_id);
        if(empty($info)){
            $this->G->error("video_not_found");
            return null;
        }
        if($view_group == $info['view_group'] || $info['view_group'] == 'all'){
            $this->G->error("role_error");
            return null;
        }
        if($info['enabled'] !== 1){
            $this->G->error("video_disabled");
            return null;
        }
//        $info['author'] = empty($info['author_id'] > 0) ? $this->UserCache->getVal($info['author_id'], null, 'UserInfos') : [];
        $info['img'] = empty($info['img']) ? '' : $this->G->getImgUrl($info['img']);
        $info['add_time'] = date('Y-m-d H:i:s', $info['add_time']);
        $this->G->success('Success', $info);
    }

    /*
     * create by phpstorm
     * author：Ming
     * date：2018.10.11
     * ps：新增视频
     * */
    private function getvideoinfo($fileid = null)
    {
        $tencentcloud = Configure::read('TencentCloud');
        $Nonce = rand(111111,999999);
        $time = time();
        $str = 'Action=GetVideoInfo&Nonce='.$Nonce.'&Region=cd&SecretId='.$tencentcloud['secret_id'].'&Timestamp='.$time .'&fileId='.$fileid.'&infoFilter.0=basicInfo';
        $srcStr = 'GETvod.api.qcloud.com/v2/index.php?'.$str;
        $signStr = base64_encode(hash_hmac('sha1', $srcStr, $tencentcloud['secret_key'], true));
        $signStr = urlencode($signStr);
        $http = new Client();
        $response = $http->get('https://vod.api.qcloud.com/v2/index.php?'.$str.'&Signature='.$signStr);
        return $response->json;
    }
}
?>